/**
 * 图层
 */
var map, mapLayer, searchObjLayer;// 基础图层
var selectedLayer, weatherLayer;// 模块通用图层
var heatMapLayer, heatGridLayer;// 热点图层
var queryRectangleLayer;// 矩形查询图层
var affectSizeLayer;// 地图遮罩图层
var mapClusterLayer;// MyCluster.js图层 (自定义聚散点图层)
var animatorLayer;// 动画图层
var pieLayer;// pie图图层
// var animatorLineLayer;
// var animatorDefaultLayer;

var bar3DLayer;// 柱状图图层，现废弃
var elementsDiv;
var echartPieLayer;

/**
 * 模块管理器
 */
var faultAlarmMan = null;// 故障滚动条
var dailyFaultMan = null;// 保护日报
var iceWarningMan = null;// 覆冰预警
var thunderWarningMan = null;// 雷击预警
var typhoonForecastMan;// 台风预警
var weatherMan = null;// 气象预警
var faultDiscMan = null;// 故障分布
var weatherDiscMan;// 气象历史
var typhoonDiscMan;// 台风历史
var riskAlarmMan = null;// 风险告警
var riskEvaluateMan = null;// 风险评估
var travelingFaultDiscMain = null;//行波故障分布

var protectionStatusMan;// 保护状态，现废弃
var faultChartMan = null;// 故障引用Pop加柱状图，现废弃
var weatherHistoryMan = null;// 用来画所有的气象站的方法，现废弃

/**
 * 窗口
 */
var infowin, infowinPosition;
var multiInfoWins = [];
var hoverDiv = new HoverDiv();// 故障滚动条用来显示浮动窗的

/**
 * 当前地图状态
 */
var mapIsLoad = false;
var currentLonlat;
var currentMousePosition;
var currentZoomLevel;
var currentExtent;

/**
 * 地图控件
 */
var queryRectangle;// 矩形查询控件
var drawMeasureLine;// 测距时用到的 动态画线控件
var selectFeature;// 地图选择控件

/**
 * 地图初始化时需要的数据
 */
// var towerLayerName = 'tower500@China4326';
// var line500LayerName='line500@China4326';
// var line500LoopLayerName='line500_loop_2@China4326';
// var station500LayerName="station500@China4326";
var mapurl = "";
var stations500 = []; //地图上500 kV变电站的定位等
var towerpoints500 = [];
var lines500 = [];

/**
 * 地图搜索框
 */
var searchSubjects = [];// [{id: "someId1", name: "Display name 1"}, {id:
// "someId2", name: "Display name 2"}]
var $inputSearch = $("#input_search");

function init() {
	$.getJSON("/rest/getMapUrl?time=" + new Date().getTime(), function(result) {
		mapurl = result['mapURL'];
		getData();
		initFaultAlarm();// 故障滚动条
		initMap();
	});
}
function initMap() {
	/**
	 * 初始化地图
	 */
	map = new SuperMap.Map("map", {
		controls : [
		// new SuperMap.Control.LayerSwitcher(),
		new SuperMap.Control.ScaleLine(),
		// new SuperMap.Control.Zoom(),
		new SuperMap.Control.Navigation({
			dragPanOptions : {
				enableKinetic : true
			}
		}) ],
		// 设置地图的可视范围
		maxExtent : new SuperMap.Bounds(96.47831261158, 16.9636416435242,
				118.82450401783, 30.9821963310242),
		restrictedExtent : new SuperMap.Bounds(87.40214, 10.85752, 127.73783,
				39.44801)
	});
	mapLayer = new SuperMap.Layer.TiledDynamicRESTLayer("China_nwld_100",
			mapurl, {
				transparent : true,
				cacheEnabled : true
			}, {
				maxResolution : "auto"
			});
	mapLayer.events.on({
		"layerInitialized" : addLayer,
		"loadError" : loadMapError,
	});

	/**
	 * 添加地图监听事件
	 */
	map.events.on({
		'click' : onMapClick
	});
	map.events.on({
		'mouseup' : function(e) {
			currentLonlat = map.getLonLatFromPixel(new SuperMap.Pixel(e.xy.x,
					e.xy.y));
		}
	});
	map.events.on({
		'mousemove' : function(e) {
			currentMousePosition = new SuperMap.Pixel(e.xy.x, e.xy.y);
			currentLonlat = map.getLonLatFromPixel(currentMousePosition);
		}
	});
	map.events.on({
		'moveend' : zoomMove
	});
	map.events.on({
		'zoomend' : zoomEnd
	});

	/**
	 * 根据业务需要，添加地图图层和控件
	 */
	queryRectangleLayer = new SuperMap.Layer.Vector("查询图层");
	queryRectangle = new SuperMap.Control.DrawFeature(queryRectangleLayer,
			SuperMap.Handler.Box);
	queryRectangle.events.on({
		"featureadded" : queryRectangleCompleted
	});
	map.addControl(queryRectangle);
	map.addControl(new SuperMap.Control.MousePosition());

	// 距离测量的画线控件;这里DrawFeature(图层,类型,属性)；multi:true在将要素放入图层之前是否现将其放入几何图层中
	drawMeasureLine = new SuperMap.Control.DrawFeature(queryRectangleLayer,
			SuperMap.Handler.Path, {
				multi : true
			});
	drawMeasureLine.events.on({
		"featureadded" : drawMeasureLineCompleted
	});
	map.addControl(drawMeasureLine);

	searchObjLayer = new SuperMap.Layer.Vector("搜索结果展示图层");

	weatherLayer = new SuperMap.Layer.Vector("天气图层", {
		"radius" : 45,
		"featureWeight" : "value",
		"featureRadius" : "geoRadius"
	});
	weatherLayer.setVisibility(false);

	selectedLayer = new SuperMap.Layer.Vector("选择事件图层");

	var callbacks = {
		over : function(currentFeature) {
			if (currentFeature.layer) {
				switch (currentFeature.layer.id) {
				case selectedLayer.id:
					onSelectedHoverListener(currentFeature);
				}
			}
		},
		out : function(currentFeature) {
			if (currentFeature.layer) {
				switch (currentFeature.layer.id) {
				case selectedLayer.id:
					onSelectedOutListener(currentFeature);
				}
			}
		},
		click : function(currentFeature) {
			switch (currentFeature.layer.id) {
			case selectedLayer.id:
				onSelectedFeature(currentFeature);
			case weatherLayer.id:
				onWeatherClickListener(currentFeature);
			}
		}
	};
	selectFeature = new SuperMap.Control.SelectFeature([ selectedLayer,
			weatherLayer ], {
		callbacks : callbacks,
		onSelect : function(currentFeature) {
			switch (currentFeature.layer.id) {
			case selectedLayer.id:
				onSelectedFeature(currentFeature);
			case weatherLayer.id:
				onWeatherClickListener(currentFeature);
			}
		},
		allowSelectTheSameFeature : true,
	});
	map.addControl(selectFeature);

	affectSizeLayer = new SuperMap.Layer.Vector("遮罩图层");

	mapClusterLayer = new SuperMap.Layer.Vector("自定义聚散点图层");

	heatMapLayer = new SuperMap.Layer.HeatMapLayer("热点图层", {
		"radius" : 45,
		"featureWeight" : "value",
		"featureRadius" : "geoRadius"
	});

	heatGridLayer = new SuperMap.Layer.HeatGridLayer("热点网格");
	heatGridLayer.gridHeight = 50;
	heatGridLayer.gridWidth = 50;
	heatGridLayer.spreadZoom = 10;

	bar3DLayer = new SuperMap.Layer.Graph("3D图层", "Bar3D");
	bar3DLayer.themeFields = [ "NUM" ];// 指定用于bar的数据字段
	bar3DLayer.chartsSetting = {
		width : 30,// 必设
		height : 100,// 必设
		codomain : [ 0, 5 ],// 必设 允许图表展示的值域范围，此范围外的数据将不制作图表
		xShapeBlank : [ 0, 0, 0 ], // 水平方向上的空白间距参数
		YOffset : -50, // 向上偏移 50像素
		useAxis : false, // 不显示坐标轴
		useBackground : false, // 不显示背景框
		barHoverAble : true
	};
	bar3DLayer.on("click", onBar3DClickListener);

	// echart图形层
	echartPieLayer = new SuperMap.Layer.Elements("eCharts");
	// 获取 Elements 图层 div
	elementsDiv = echartPieLayer.getDiv();
	// 设置Elements实例的div为地图大小
	var mapsize = map.getSize();
	elementsDiv.style.width = mapsize.w;
	elementsDiv.style.height = 300;

	animatorLayer = new SuperMap.Layer.AnimatorVector("时空数据", {
		rendererType : "StretchLine"
	}, {
		repeat : false,// 重复播放
		speed : 0.5,// 每帧播放0.05的数据
		frameRate : 12,// 每秒渲染12帧
		startTime : 0,
		endTime : 10
	});
	animatorLayer.events.on({
		"drawfeaturestart" : drawAnimatorFeatureStart,
		"featurerendered" : featurerendered
	});

	// animatorLineLayer = new SuperMap.Layer.AnimatorVector("线路动画图层",
	// {rendererType:"StretchLine"},{
	// repeat:false,//重复播放
	// speed:0.05,//每帧播放0.05的数据
	// frameRate:60,//每秒渲染12帧
	// startTime:0,
	// endTime:10
	// });
	// animatorLineLayer.setVisibility(true);
	//	
	// animatorDefaultLayer = new SuperMap.Layer.AnimatorVector("默认动画图层",
	// {rendererType:"AnimatorCanvas"},{
	// repeat:false,//重复播放
	// speed:0.05,//每帧播放0.05的数据
	// frameRate:60,//每秒渲染12帧
	// startTime:0,
	// endTime:10
	// });
	// animatorDefaultLayer.setVisibility(true);

	pieLayer = new SuperMap.Layer.Graph("pieLayer", "Pie");
	pieLayer.chartsSetting = {
		width : 20,// 必设
		height : 20,// 必设
		codomain : [ -1, 9999 ], // 必设 允许图表展示的值域范围，此范围外的数据将不制作图表
		sectorStyle : {
			fillOpacity : 1
		},// 饼图扇形样式
		// 按字段设置饼图扇形 (样式与 themeLayer.themeFields 数组中的字段名称一一对应)
		// sectorStyleByFields: [{ fillColor: "#0000FF" }, { fillColor:
		// "#FFFF00" }, { fillColor: "#FF0000" },{fillColor:"#008000"}],
		// sectorStyleByFields:sectorStyleByFields,//该变量在风险评估里面
		sectorHoverAble : false,// 饼图是否开启hover
		sectorHoverStyle : {
			fillOpacity : 1
		}
	};// hover时，饼图样式
	pieLayer.on("click", onPieLayerClickListener);
}
function addLayer() {
	mapIsLoad = true;
	map.addLayers([ mapLayer, heatMapLayer, weatherLayer, selectedLayer,
			mapClusterLayer, searchObjLayer, queryRectangleLayer,
			affectSizeLayer, bar3DLayer, animatorLayer, heatGridLayer,
			echartPieLayer, pieLayer ]);
	setCenter();
}
function loadMapError() {
	mapIsLoad = false;
	getData();
}
/**
 * 重新回到地图初始缩放状态
 */
function backToDefaultZoom() {
	if (mapIsLoad) {
		setCenter();
	}
}
/**
 * 设置地图中心点和缩放级别
 */
function setCenter() {
	map.setCenter(new SuperMap.LonLat(107.09076285156, 23.808358533712), 8);
}
/**
 * 初始化线路数据，以及地图各个模块告警数量数据
 */
function getData() {
	getStations();
	getLines();
	getWeatherWarningCountByDate();
	getIceWarningCount();
	getRiskAlarmCount();
	getTyphoonWarningCount();
	getThunderWarningCount();
	$inputSearch.typeahead({
		source : searchSubjects,
		autoSelect : false
	});
	showNewEquipmentAlarm(true);
}
function genEquipmentUpdateInfo(result) {
	var html = '';
	if (result && result.length > 0) {
		for ( var r in result) {
			html += '<li><span style="display: inline-block; width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">'
					+ result[r].name
					+ '</span>'
					+ '<span class="pull-right" style="display: inline-block;">'
					+ DateUtil.dateTime(result[r].updateTime) + '</span></li>';
		}
	} else {
		html = '<li><span  style="display: inline-block;">最近无设备更新记录</span></li>';
	}
	return html;
}

/**
 * 主页--设备更新提醒
 *
 * @returns
 */
function showNewEquipmentAlarm(forceShow) {

	var equipmentdiv = $('#newEquipmentAlarm');
	var equipmentUL = $('#equipmentUL');
	$.getJSON('/rest/cim/findLast3DaysMessages', function(result) {
		if (result && result.length > 0) {
			if (forceShow) {
				equipmentUL.html(genEquipmentUpdateInfo(result));
				equipmentdiv.css('display', 'block');
			} else if (checkShowNewEquipmentAlarm(result[0].updateTime)) {
				equipmentUL.html(genEquipmentUpdateInfo(result));
				setShowNewEquipmentAlarmTime(result[0].updateTime);
			} else {
				equipmentdiv.css('display', 'none');
			}
		}
	});
}
/**
 *  1.查询更新的设备 2.判断这个是不是应该提示
 * (1)根据usercode获得localStorage,localStorage[usercode],get出来应该是一个时间戳，得到时间戳之后，判断是否跟当前排序的第0位时间一样
 * (2)如果一样，则不显示，如果不一样，就显示 (3)显示之后更新这个时间戳
 */
function checkShowNewEquipmentAlarm(newEquipmentAlarmTime) {
	var localObj = {};
	var localStr = localStorage.getItem('newEquipmentAlarmTime');
	//	console.log(userCode);
	if (localStr) {
		localObj = JSON.parse(localStr);
	}
	// 拿到浏览器缓存中存储的newEquipmentAlarmTime，如果相同返回false，如果不相同则返回true
	if (localObj[userCode] == newEquipmentAlarmTime) {
		return false;
	} else {
		return true;
	}
}

/**
 * 新设备更新提示--显示之后更新这个时间戳
 * @param newEquipmentAlarmTime
 * @returns
 */
function setShowNewEquipmentAlarmTime(newEquipmentAlarmTime) {
	var localObj = {};
	localObj = localStorage.getItem('newEquipmentAlarmTime');
	if (localObj) {
		localObj[userCode] = newEquipmentAlarmTime;
	} else {
		localObj = {};
		localObj[userCode] = newEquipmentAlarmTime;
		localStorage.setItem('newEquipmentAlarmTime', JSON.stringify(localObj));
	}
}

/**
 * 隐藏新设备更新提示框
 * @returns
 */
function hideNewEquipmentAlarm() {
	var equipmentdiv = $('#newEquipmentAlarm');
	equipmentdiv.css('display', 'none');
}

function getStations() {
	$.getJSON("/rest/getStations/500", function(result) {
		stations500 = result;
		for ( var i in stations500) {
			addToSearchs(stations500[i].name, stations500[i].name, true);
		}
	});
}
function getLines() {
	$.getJSON("/rest/getLineByVoltage/500", function(result) {
		lines500 = result;
		for ( var i in lines500) {
			addToSearchs(lines500[i].lineName, lines500[i].lineName, true);
			towerpoints500 = towerpoints500.concat(lines500[i].towers);
		}
	});
}

/**
 * 初始化告警数量
 */
function getWeatherWarningCountByDate() {
	$.getJSON("/rest/getWeatherWarningCountByDate", function(result) {
		if (Number(result) > 0) {
			$("#zym_qxyjnum").text(result);
		}
	});
}
function getIceWarningCount() {
	$.getJSON("/rest/ice/getIceWarningCount", function(result) {
		if (Number(result) > 0) {
			$("#zym_qxyj_fbyjnum").text(result);
		}
	});
}
function getRiskAlarmCount() {
	$.getJSON("/rest/riskwarning/getRiskAlarmCount", function(result) {
		var n1 = Number(result[0]);
		var n2 = Number(result[1]);
		if (n1 > 0) {
			$("#zym_fxgj_ycsbnum").text(n1);
		}
		if (n2 > 0) {
			$("#zym_fxgj_ecsbnum").text(n2);
		}
		if (n1 + n2 > 0) {
			$("#zym_fxgjnum").text(n1 + n2);
		}
	});
}
function getTyphoonWarningCount() {
	$.getJSON("/rest/TyphoonRestService/getTyphoonWarningCount", function(
			result) {
		if (Number(result) > 0) {
			$("#zym_tfyjnum").text(result);
		}
	});
}
function getThunderWarningCount() {
	$.getJSON("/rest/thunder/getThunderWarningCount", function(result) {
		if (Number(result) > 0) {
			$("#zym_ldyjnum").text(result);
		}
	});
}

function onMapClick(e) {
	infowinPosition = e.xy.clone();
	// 偏移
	infowinPosition.x += 40;
	infowinPosition.y -= 25;
	currentMousePosition = new SuperMap.Pixel(e.xy.x, e.xy.y);
	currentLonlat = map.getLonLatFromPixel(currentMousePosition);
	var sp = 0.04;
	if (map.getZoom() > 10) {
		sp = 0.004;
	}

	var x = currentLonlat.lon - sp;
	var y = currentLonlat.lat - sp;
	var w = sp * 2;
	var h = sp * 2;
	var rectangle = new SuperMap.Geometry.Rectangle(x, y, w, h);

	var currentQueryBounds = rectangle.getBounds();
	onMapQueryObjByBounds(currentQueryBounds);
}
/**
 * 地图点击或矩形查询时，菜单显示
 */
function onMapQueryObjByBounds(currentQueryBounds) {
	var sts = findStationsByBounds(currentQueryBounds);
	if (sts && sts.length > 0) {
		//点击变电站后展示二级菜单，暂时注释
		//openStationMenuWin(sts[0]);
	} else {
		var lns = findLinesByBounds(currentQueryBounds);
		if (lns && lns.length > 0) {
			openSelectLineWin(lns, {
				lon : currentQueryBounds.left,
				lat : currentQueryBounds.top
			});
		}
	}
}

/**
 * 查询区域内的变电站集合
 */
function findStationsByBounds(queryBounds) {
	var cExtent = queryBounds;
	var containsSt = [];
	for (var i = 0; i < stations500.length; i++) {
		if (cExtent.contains(stations500[i].longitude, stations500[i].latitude,
				true)) {
			containsSt.push(stations500[i]);
		}
	}
	return containsSt;
}
/**
 * 查询区域内的线路对应杆塔的map集合，根据线路的杆塔坐标 return Map<[lineid,linename],[t1,t2...]>
 */
function findLineTowerMapByBounds(queryBounds) {
	var cExtent = queryBounds;
	var lineTowerMap = new Map();
	for (var i = 0; i < towerpoints500.length; i++) {
		if (cExtent.contains(towerpoints500[i].longitude,
				towerpoints500[i].latitude, true)) {
			var key = [ towerpoints500[i].lineId, towerpoints500[i].lineName ];
			var ts = lineTowerMap.get(key);
			if (!ts) {
				ts = [];
				lineTowerMap.put(key, ts);
			}
			ts.push(towerpoints500[i].towerno);
		}
	}
	return lineTowerMap;
}
/**
 * 查询区域内的线路集合，根据线路的杆塔坐标
 * 
 * @param queryBounds
 * @returns {Array}
 */
function findLinesByBounds(queryBounds) {
	var cExtent = queryBounds;
	var lines = [];
	for (var i = 0; i < lines500.length; i++) {
		var points = lines500[i].towers;
		if (points.length > 2) {
			for (var j = 1; j < points.length; j++) {
				var p1 = points[j - 1];
				var p2 = points[j];
				var bounds = new SuperMap.Bounds();
				bounds.extend(new SuperMap.Geometry.Point(p1.longitude,
						p1.latitude));
				bounds.extend(new SuperMap.Geometry.Point(p2.longitude,
						p2.latitude));
				var isIntersects = bounds.intersectsBounds(cExtent);
				if (isIntersects) {
					lines.push(lines500[i]);
					break;
				}
			}
		}
		// for(var j in ts){
		// if(cExtent.contains(ts[j].longitude,
		// ts[j].latitude,true)){
		// lines.push(lines500[i]);
		// break;
		// }
		// }

	}
	return lines;
}

function searchObj(notDrawStation, notZoom) {
	var name = $("#input_search").val();
	searchSelectObj(name, notDrawStation, notZoom, name);
}
function clearSearchObj(nameOrId) {
	if (nameOrId) {
		var fs = searchObjLayer.features;
		var arr = [];
		for (var i = 0; i < fs.length; i++) {
			if (fs[i].data.series == "searchObj" + nameOrId
					|| fs[i].data.seriesId == "searchObj" + nameOrId) {
				arr.push(fs[i]);
			}
		}
		searchObjLayer.removeFeatures(arr);
	} else {
		$inputSearch.val('');
		searchObjLayer.removeAllFeatures();
		clearQueryStatus();
	}
}
/**
 * 搜索地图线路或变电站
 * 
 * @param name 搜索的线路或变电站名 或者线路或变电站的id
 * @param notDrawStation 搜索到变电站时，不绘出变电站的红点
 * @param notZoom 搜索到对象时，不进行以对象为中心的地图的放缩
 */
function searchSelectObj(name, notDrawStation, notZoom, id, isShowFaultInfo) {
	if (name && name.length > 0) {
		var notfind = true;
		try {
			for (var i = 0; i < stations500.length; i++) {
				var s = stations500[i];
				if (s.name.indexOf(name) > -1
						|| (id != null && id + "" === s.id + "")) {
					// 判断变电站的经纬度是否为空
					if (!s.longitude && !s.latitude) {
						showGisErrorInfo(name);
						return;
					} else {
						if (!notZoom) {
							map.setCenter(new SuperMap.LonLat(s.longitude,
									s.latitude), 10);
						}
						if (!notDrawStation) {
							drawStation(s);
						}
						return;
					}

				}
			}
			for (var i = 0; i < lines500.length; i++) {
				var obj = lines500[i];
				if (obj.lineName.indexOf(name) > -1
						|| (id != null && id + "" === obj.lineId + "")) {
					draw_acline_one(lines500[i]);
					if (!notZoom) {
						var ts = lines500[i].towers;
						var left = ts[0].longitude;
						var right = ts[0].longitude;
						var top = ts[0].latitude;
						var bottom = ts[0].latitude;
						for (var i = 0; i < ts.length; i++) {
							if (ts[i].longitude < left) {
								left = ts[i].longitude;
							}
							if (ts[i].longitude > right) {
								right = ts[i].longitude;
							}
							if (ts[i].latitude > top) {
								top = ts[i].latitude;
							}
							if (ts[i].latitude < bottom) {
								bottom = ts[i].latitude;
							}
						}
						// x:y = 2:1
						var width = right - left;
						var height = top - bottom;
						if (2 * height > width) {
							width = 2 * height;
							var center = width / 2 + left;
							left = center - height;
							right = center + height;
						} else {
							var center = height / 2 + bottom;
							bottom = center - width / 2;
							top = center + width / 2;
						}
						var bounds = new SuperMap.Bounds(left - 0.05,
								bottom - 0.05, right + 0.05, top + 0.05);
						map.zoomToExtent(bounds);
					}
					return;
				}
			}
		} catch (e) {
		}

		if (notfind && isShowFaultInfo) {
			showGisErrorInfo(name);
		}
	}
}
function showGisErrorInfo(name) {
	backToDefaultZoom();
	layer.msg('获取   <b>' + name + '</b>   地理信息失败', {
		shadeClose : true,
		shade : 0.2,
		icon : 5
	});
	/*
	 * var content = "获取 "+name+" 地理信息失败"; var contentHTML = "<div
	 * style='width:300px;color:red;font-size:24px;text-align:center; opacity:
	 * 0.8'>"; contentHTML += content; contentHTML += "</div>"; var popup = new
	 * SuperMap.Popup("chicken", new SuperMap.LonLat(107.09076285156,
	 * 23.808358533712), null,contentHTML , false); popup.closeOnMove = true;
	 * popup.autoSize = true; popup.closeBox = false; infowin = popup;
	 * map.addPopup(popup);
	 */
}
function zoomEnd() {
	hoverDiv.hide();
	if (typhoonDiscMan && typhoonDiscMan.isShow()) {
		typhoonDiscMan.refreshPop();
	}
}
function zoomMove() {
	clearQueryStatus();
	currentZoomLevel = map.getZoom();
	currentExtent = map.getExtent();
	if (weatherDiscMan && weatherDiscMan.isShow()) {
		weatherDiscMan.zoom();
	}
	if (faultChartMan && faultChartMan.isShow()) {
		faultChartMan.show();
	}
	if (weatherHistoryMan) {
		weatherHistoryMan.zoom(currentZoomLevel);
	}
	if (dailyFaultMan) {
		dailyFaultMan.zoom(currentZoomLevel);
	}
	hoverDiv.hide();
	if (typhoonDiscMan && typhoonDiscMan.isShow()) {
		typhoonDiscMan.refreshPop();
	}
}

function initFaultAlarm() {
	faultAlarmMan = new FaultAlarmMan().show();
}

/**
 * 图层事件
 */
function onSelectedHoverListener(currentFeature) {
	closeInfoWin();
	var obj = currentFeature.geometry;
	var lonlat = null;
	if (obj.x) {
		lonlat = new SuperMap.LonLat(obj.x, obj.y);
	} else if (currentLonlat) {
		lonlat = currentLonlat;
	}
	var type = currentFeature.data.type;
	if (!type) {
		return;
	}
	if (type.indexOf("typhoonF") > -1) {
		typhoonForecastMan.onHoverPoint(currentFeature);
	} else if (type.indexOf("typhoonD") > -1) {
		typhoonDiscMan.onHoverPoint(currentFeature);
	}
}
function onSelectedOutListener(currentFeature) {
	closeInfoWin();
	var obj = currentFeature.geometry;
	var lonlat = null;
	if (obj.x) {
		lonlat = new SuperMap.LonLat(obj.x, obj.y);
	} else if (currentLonlat) {
		lonlat = currentLonlat;
	}
	var type = currentFeature.data.type;
	if (!type) {
		return;
	}
	if (type && type.indexOf("typhoonF") > -1) {
		typhoonForecastMan.onOutPoint(currentFeature);
	} else if (type.indexOf("typhoonD") > -1) {
		typhoonDiscMan.onOutPoint(currentFeature);
	}
}
function onWeatherClickListener(currentFeature) {
	closeInfoWin();
	var obj = currentFeature.geometry;
	var lonlat = null;
	if (obj.x) {
		lonlat = new SuperMap.LonLat(obj.x, obj.y);
	} else if (currentLonlat) {
		lonlat = currentLonlat;
	}
	var type = currentFeature.data.type;
	if (!type) {
		return;
	}
	if (type == "weather") {
		if (weatherMan) {
			weatherMan.openWeatherInfoWin(currentFeature.data.value);
		}
	} else if (type == "faultResaon") {
		openFaultResonWin(currentFeature.data.value, lonlat);
	} else if (type == "daily") {
		var d = currentFeature.data;
		dailyFaultMan.openPop(d.group, d.groupType, d.value);
	} else if (type.indexOf("riskAlarmPoint") > -1) {
		riskAlarmMan.openPop(currentFeature);
	} else if (type == "faultAlarm") {
		faultAlarmMan.clickPoint(currentFeature.data.value);
	} else if (type == "iceMonitor") {
		iceWarningMan.openMonitorDialog(currentFeature.data.value);
	}
}
function onSelectedFeature(currentFeature) {
	var type = currentFeature.data.type;
	if (type == 'primary' || type == 'secondary' || type == 'special') {
		riskEvaluateMan.openRiskEvalutationDlg(currentFeature);
	} else if (type.indexOf('protectionStatus') > -1) {
		protectionStatusMan.onSelectPoint(currentFeature.data.value);
	} else if (type && type.indexOf('typhoonD') > -1) {
		typhoonDiscMan.onSelectPoint(currentFeature);
	} else if (type && type.indexOf('typhoonF') > -1) {
		typhoonForecastMan.onSelectPoint(currentFeature);
	} else if (type.indexOf("primeType") > -1
			|| type.indexOf("secondType") > -1) {
		riskEvaluateMan.openRiskEvalutationDlg(currentFeature);
	}
}
/**
 * 风险评估--一次设备/二次设备 地图上的pie点击事件
 * 调用 riskEvaluateMan --> openPieDlg
 * @param e
 * @returns
 */
function onPieLayerClickListener(e) {
	if (e.target) {
		var currentFeature = pieLayer.getFeatureById(e.target.refDataID);
		var type = currentFeature.data.type;
		if (type == 'primary' || type == 'secondary') {
			riskEvaluateMan.openPieDlg(currentFeature);
		}
	}
}
function onBar3DClickListener(e) {
	if (e.target && e.target.refDataID) {
		var feature = bar3DLayer.getFeatureById(e.target.refDataID);
		dailyFaultMan.openPop({
			stationIdOrAreaValue : feature.data.NAME
		}, 'dailyexceed');
	}
}
function featurerendered(feature) {
	var featureId = feature.attributes["FEATUREID"];
	if (featureId.indexOf('typhoonD') > -1) {
		typhoonDiscMan.featureRendered(feature);
	}
}
function drawAnimatorFeatureStart(feature) {
	if (!animatorLayer.animator.getRunning()) {
		return;
	}
	var featureId = feature.attributes["FEATUREID"];
	if (featureId.indexOf('typhoonD') > -1) {
		typhoonDiscMan.onDrawAnimator(feature);
	} else if (featureId.indexOf('typhoonF') > -1) {
		typhoonForecastMan.onDrawAnimator(feature);
	}
}
/**
 * 打开变电站功能菜单
 * 
 * @param station
 */
function openStationMenuWin(station) {
	closeInfoWin();
	var lonlat = new SuperMap.LonLat(station.longitude, station.latitude);
	if (!lonlat) {
		lonlat = currentLonlat;
	}
	// checkPosition(lonlat);
	var pop = new Popup(lonlat.lon, lonlat.lat);
	pop.setCloseOnMove(true);
	pop.hasArrow(false);
	pop.setTitle(station.name);
	pop.setRowContent("站内接线图").setRowClickListener(
			'openStationSecondSvg(\'' + station.id + '\')');
	pop.setRowContent("断路器动作分析").setRowClickListener(
			'openBreakerDlg(\'' + station.id + '\',\'' + station.name + '\')');
	pop.setRowContent("特维分析")
			.setRowClickListener(
					'openBreakerSmDlg(\'' + station.id + '\',\'' + station.name
							+ '\')');
	pop.setRowContent("保护响应特性").setRowClickListener(
			'openProtectDlg(\'' + station.id + '\',\'' + station.name + '\')');
	pop.show();
	infowin = pop.getPop();
	/*
	 * var content = "<div class=\"box\">" +"<div class=\"box-header\">" +
	 * station.name +"</div>" +"<div class=\"box-body\">" +"<a
	 * href='javascript:void(0);' onclick='openStationPrimSvg("+station.id+")'
	 * class=\"btn btn-block btn-social btn-dropbox\">" +"<i class=\"fa
	 * fa-file-image-o\"></i> 一次接线图" +"</a>" +"<a href='javascript:void(0);'
	 * onclick='openStationSecondSvg("+station.id+")' class=\"btn btn-block
	 * btn-social btn-dropbox\">" +"<i class=\"fa fa-file-image-o\"></i>
	 * 站内接线图" +"</a>" +"<a href='javascript:void(0);'
	 * onclick='openBreakerDlg(\""+station.id+"\",\""+station.name+"\")'
	 * class=\"btn btn-block btn-social btn-dropbox\">" +"<i class=\"fa
	 * fa-file-image-o\"></i> 断路器动作分析" +"</a>" +"<a
	 * href='javascript:void(0);'
	 * onclick='openBreakerSmDlg(\""+station.id+"\",\""+station.name+"\")'
	 * class=\"btn btn-block btn-social btn-dropbox\">" +"<i class=\"fa
	 * fa-file-image-o\"></i> 特维分析" +"</a>" +"<a href='javascript:void(0);'
	 * onclick='openProtectDlg(\""+station.id+"\",\""+station.name+"\")'
	 * class=\"btn btn-block btn-social btn-dropbox\">" +"<i class=\"fa
	 * fa-file-image-o\"></i> 保护响应特性" +"</a>" +"</div>" +"</div>"; var popup =
	 * new SuperMap.Popup("chicken", lonlat, null,content , false);
	 * popup.closeOnMove = true; popup.autoSize = true; popup.closeBox = false;
	 * infowin = popup; map.addPopup(popup);
	 */
}
function openStationPrimSvg(sid) {
	var ps = [];
	ps.push({
		name : "stationId",
		value : sid
	});
	ps.push({
		name : "svgType",
		value : 1
	});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200",
			"700", JSON.stringify(ps));
	openDialog(params);
}
function openStationSecondSvg(sid) {
	var ps = [];
	ps.push({
		name : "stationId",
		value : sid
	});
	ps.push({
		name : "svgType",
		value : 2
	});
	var params = MyModal.getModalParam("/ui/map/dialog/svg.xhtml", "1200",
			"700", JSON.stringify(ps));
	openDialog(params);
}
function openBreakerDlg(sid, sname) {
	var ps = [];
	ps.push({
		name : "stationId",
		value : sid
	});
	ps.push({
		name : "stationName",
		value : sname
	});
	var params = MyModal.getModalParam("/ui/map/dialog/breaker.xhtml", "1200",
			"700", JSON.stringify(ps));
	openDialog(params);
	// MyModal.showModal("/ui/map/dialog/breaker.xhtml",
	// "1200","700",JSON.stringify(ps));
}
function openBreakerSmDlg(sid, sname) {
	var ps = [];
	ps.push({
		name : "stationId",
		value : sid
	});
	ps.push({
		name : "stationName",
		value : sname
	});
	var params = MyModal.getModalParam(
			"/ui/map/dialog/statSpecialMaintain.xhtml", "1000", "550", JSON
					.stringify(ps));
	openDialog(params);
}
function openProtectDlg(sid, sname) {
	var ps = [];
	ps.push({
		name : "stationId",
		value : sid
	});
	ps.push({
		name : "stationName",
		value : sname
	});
	var params = MyModal.getModalParam(
			"/ui/map/dialog/statProtectResponse.xhtml", "1200", "700", JSON
					.stringify(ps));
	openDialog(params);
}

function openFaultResonWin(fault, lonlat) {
	closeInfoWin(false);
	var ft = 0;
	if (fault.faultTime.time) {
		ft = new Date(fault.faultTime.time);
	} else {
		ft = new Date(fault.faultTime);
	}
	var pop = new Popup(lonlat.lon, lonlat.lat);
	pop.hasArrow(false);
	pop.setCloseOnMove(true);
	pop.showHoverEffect(false);
	pop.showRowOverflow(false);
	var div = $("<div></div>");
	div.append("故障时间: " + ft.toLocaleString() + "<br />");
	div.append("故障类型: " + fault.faultType + "<br />");
	div.append("故障原因: " + fault.faultReson + "<br />");
	div.append("故障相别: " + fault.faultPhase + "<br />");
	div.append("<div style='width:300px;'>备注：" + fault.remark + '</div>');
	pop.setRowContent(div.html());
	var ps = [];
	ps.push({
		name : "faultTime",
		value : DateUtil.dateTime(fault.faultTime)
	});
	ps.push({
		name : "lineId",
		value : fault['equipment_id']
	});
	var params = MyModal.getModalParam(
			"/ui/map/protectActSvg/protectActSvg.xhtml", null, null, JSON
					.stringify(ps));
	pop
			.setRowContent("<div style='height:37px;'><a href='javascript:void(0)' onclick='openDialog("
					+ JSON.stringify(params)
					+ ")' class='btn btn-sm btn-info btn-flat pull-left'>故障分析</a></div>");
	pop.show();
	infowin = pop.getPop();
}
/**
 * 将汉字转化为unicode
 * 
 * @param str
 * @returns
 */
function ch2Unicdoe(str) {
	if (!str) {
		return;
	}
	var unicode = '';
	for (var i = 0; i < str.length; i++) {
		var temp = str.charAt(i);
		if (isChinese(temp)) {
			unicode += '\\u' + temp.charCodeAt(0).toString(16);
		} else {
			unicode += temp;
		}
	}
	return unicode;
}

/**
 * 判断字符是否为汉字
 */
function isChinese(s) {
	return /[\u4e00-\u9fa5]/.test(s);
}

/**
 * 打开线路功能菜单
 * 
 * @param lineObject
 * @param plonlat
 */
function openLineInfoWin(lineObject, plonlat) {
	closeInfoWin();
	lonlat = currentLonlat;
	if (!lineObject.lineName) {
		lineObject = JSON.parse(lineObject);
	}

	var ps = [];
	ps.push({
		name : "selectId",
		value : lineObject.lineId
	});
	ps.push({
		name : "selectName",
		value : encodeURIComponent(encodeURIComponent(lineObject.lineName))
	});
	var params = MyModal.getModalParam(
			"/ui/map/dialog/lineFaultHisDialog.xhtml", "1200", "700", JSON
					.stringify(ps));
	var params2 = MyModal.getModalParam(
			"/ui/map/dialog/protectResponseDialog.xhtml", "1200", null, JSON
					.stringify(ps));
	var params4 = MyModal.getModalParam(
			"/ui/map/dialog/lineProtectActDialog.xhtml", "1200", null, JSON
					.stringify(ps));
	var params3 = MyModal.getModalParam("/ui/map/dialog/iceFaultDialog.xhtml",
			"1000", null, JSON.stringify(ps));

	var lon = plonlat ? plonlat.lon : lonlat.lon;
	var lat = plonlat ? plonlat.lat : lonlat.lat;
	var pop = new Popup(lon, lat);
	pop.setTitle(lineObject.lineName);
	pop.setRowContent("查看历史故障").setRowClickListener(
			"showFaultReasonInMap(" + JSON.stringify(lineObject) + ")");
	pop.setRowContent("故障历史统计").setRowClickListener(
			"openDialog(" + JSON.stringify(params) + ")");
	pop.setRowContent("保护响应特性").setRowClickListener(
			"openDialog(" + JSON.stringify(params2) + ")");
	pop.setRowContent("保护动作分析").setRowClickListener(
			"MyModal.openPage(" + JSON.stringify(params4) + ")");
	/* pop.setRowContent("覆冰历史记录").setRowClickListener("openDialog("+JSON.stringify(params3)+")"); */
	pop.setCloseOnMove(true);
	pop.hasArrow(false);
	pop.show();
	infowin = pop.getPop();
}

function checkPosition(lonlat) {
	var mapcenter = map.getCenter();
	if (lonlat.lat < mapcenter.lat) {
		lonlat.lat = mapcenter.lat;
	}
}
/**
 * 打开选择线路的列表
 * 
 * @param lines
 * @param plonlat
 */
function openSelectLineWin(lines, plonlat) {
	closeInfoWin();
	if (lines) {
		if (lines.length == 1) {
			openLineInfoWin(lines[0]);
		} else {
			var lonlat = currentLonlat;
			var lon = plonlat ? plonlat.lon : lonlat.lon;
			var lat = plonlat ? plonlat.lat : lonlat.lat;
			var pop = new Popup(lon, lat);
			pop.setCloseOnMove(true);
			pop.hasArrow(false);
			pop.showRowOverflow(false);
			//线路列表的标题，暂时注释
			/*pop.setTitle("选择线路");*/
			for (var i = 0; i < lines.length; i++) {
				var btnitem = lines[i].lineName;
				pop.setRowContent(btnitem).setRowClickListener(
						//选择线路后的执行方法，暂时注释
						/*'openLineInfoWin(' + JSON.stringify(lines[i]) + ','
								+ JSON.stringify({
									lon : lon,
									lat : lat
								}) + ')'*/
								);
			}
			pop.show();
			infowin = pop.getPop();
		}
	}
}
// 关闭信息框
function closeInfoWin(isCloseMultiWin) {
	if (infowin) {
		try {
			map.removePopup(infowin);
		} catch (e) {
		}
	}
	infowin = null;
	if (isCloseMultiWin != null && isCloseMultiWin != false) {
		if (multiInfoWins.length > 0) {
			var i = 0;
			for (i in multiInfoWins) {
				try {
					multiInfoWins[i].hide();
					multiInfoWins[i].destroy();
				} catch (e) {
				}
			}
		}
		multiInfoWins = [];
	}
}
function drawStation(station) {
	// 点对象
	var lon = station.longitude;
	var lat = station.latitude;
	var name = station.name;
	var features = [];
	var point = new SuperMap.Geometry.Point(lon, lat);
	var pointVector = new SuperMap.Feature.Vector(point);
	pointVector.style = {
		fillColor : "red",
		strokeColor : "blue",
		// label : name,
		// labelAlign : 'cb',//{String} 标签对齐，是由两个字符组成的字符串，如：”lt”, “cm”, “rb”，
		// 其中第一个字符代表水平方向上的对齐，”l”=left, “c”=center, “r”=right；
		// 第二个字符代表垂直方向上的对齐，”t”=top, “m”=middle, “b”=bottom。
		// labelYOffset : 6,//{Number} 标签在y轴方向的偏移量。
		pointRadius : 8
	};
	pointVector.data.type = "station";
	pointVector.data.value = station;
	pointVector.data.series = "searchObj" + name;
	pointVector.data.seriesId = "searchObj" + station.id;
	features.push(pointVector);
	searchObjLayer.addFeatures(features);
}
function draw_acline_one(linedata) {
	var features = [];
	var points = [];
	var towers = linedata.towers;
	for (var j = 0; j < towers.length; j++) {
		var t = towers[j];
		var point = new SuperMap.Geometry.Point(t.longitude, t.latitude);
		points.push(point);
	}
	var line = new SuperMap.Geometry.LineString(points);
	var linecVector = new SuperMap.Feature.Vector(line);
	linecVector.style = {
		strokeColor : "red",
		strokeWidth : 4
	};
	linecVector.data.type = "acline";
	linecVector.data.value = linedata;
	linecVector.data.series = "searchObj" + linedata.lineName;
	linecVector.data.seriesId = "searchObj" + linedata.lineId;
	features.push(linecVector);

	var lonlats = [ linedata.stLonlat, linedata.etLonlat ];
	for (var i = 0; i < lonlats.length; i++) {
		var s = lonlats[i];
		if (!s || !s[0] || !s[1]) {
			continue;
		}
		var point = new SuperMap.Geometry.Point(s[0], s[1]);
		var pointVector = new SuperMap.Feature.Vector(point);
		pointVector.style = {
			fillColor : "red",
			strokeColor : "blue",
			pointRadius : 8
		};
		pointVector.data.type = "aclineStation";
		pointVector.data.value = linedata;
		pointVector.data.series = "searchObj" + linedata.lineName;
		pointVector.data.seriesId = "searchObj" + linedata.lineId;
		features.push(pointVector);
	}

	searchObjLayer.addFeatures(features);
}

// 画矩形
function drawQueryRectangle() {
	// 先清除上次的显示结果
	clearQueryStatus();
	queryRectangle.activate();
}
// 测距
function distanceMeasure() {
	clearQueryStatus();
	drawMeasureLine.activate();
}
function addToSearchs(key, value, isTransPinYin) {
	// 如果变电站叫：500kv木棉站，那么他的汉字key：500kv木棉站，拼音key：500kvMMZ
	// 这样的话，搜索kv的时候，会出来两个 500kv木棉站。
	// 为了防止通过一个字符，找到两个重复的变电站，将 汉字key中的非汉字去掉，变成：木棉站
	var reg = /[\u4e00-\u9fa5]/g;
	if (key) {
		try {
			if (key.match(reg)) {
				var k = key.match(reg).join("");
				searchSubjects.push({
					id : k,
					name : value
				});
			}
			if (isTransPinYin) {
				var pinyinkey = pinyinUtil.getFirstLetter(key);
				searchSubjects.push({
					id : pinyinkey,
					name : value
				});
			}
			;
		} catch (e) {
			console.log(e);
		}
	}
}

function getMousePositionPx(e) {
	infowinPosition = e.xy.clone();
	// 偏移
	infowinPosition.x += 40;
	infowinPosition.y -= 25;
	currentLonlat = map.getLonLatFromPixel(new SuperMap.Pixel(e.xy.x, e.xy.y));
}

function queryRectangleCompleted(obj) {
	queryRectangle.deactivate();
	clearQueryStatus();

	var feature = obj.feature;
	var currentQueryBounds = feature.geometry.bounds;
	onMapQueryObjByBounds(currentQueryBounds);

}
// 绘完触发事件
function drawMeasureLineCompleted(drawGeometryArgs) {
	// 停止画面控制
	drawMeasureLine.deactivate();
	// 获得图层几何对象
	var geometry = drawGeometryArgs.feature.geometry, measureParam = new SuperMap.REST.MeasureParameters(
			geometry), /* MeasureParameters：量算参数类。 客户端要量算的地物间的距离或某个区域的面积 */
	myMeasuerService = new SuperMap.REST.MeasureService(mapurl); // 量算服务类，该类负责将量算参数传递到服务端，并获取服务端返回的量算结果
	myMeasuerService.events.on({
		"processCompleted" : measureCompleted
	});

	// 对MeasureService类型进行判断和赋值，当判断出是LineString时设置MeasureMode.DISTANCE，否则是MeasureMode.AREA

	myMeasuerService.measureMode = SuperMap.REST.MeasureMode.DISTANCE;

	myMeasuerService.processAsync(measureParam); // processAsync负责将客户端的量算参数传递到服务端。
}

// 测量结束调用事件
function measureCompleted(measureEventArgs) {
	var distance = measureEventArgs.result.distance;
	var unit = '米';

	if (distance) {
		if (distance > 5000) {
			distance = distance / 1000;
			unit = '千米';
		}
	}
	// var unit = measureEventArgs.result.unit;
	closeInfoWin();
	var lonlat = currentLonlat;
	checkPosition(lonlat);
	var content = "测距结果：" + distance.toFixed(2) + unit;
	var popup = new SuperMap.Popup("chicken", lonlat, null, content, false);
	popup.closeOnMove = true;
	popup.autoSize = true;
	popup.closeBox = false;
	infowin = popup;
	map.addPopup(popup);
}
/**
 * 画圆
 */
function createCircle(origin, radius, sides, r, angel) {
	var rR = r * Math.PI / (180 * sides);
	var rotatedAngle, x, y;
	var points = [];
	for (var i = 0; i < sides; i++) {
		rotatedAngle = rR * i;
		x = origin.x + (radius * Math.cos(rotatedAngle));
		y = origin.y + (radius * Math.sin(rotatedAngle));
		points.push(new SuperMap.Geometry.Point(x, y));
	}
	rotatedAngle = r * Math.PI / 180;
	x = origin.x + (radius * Math.cos(rotatedAngle));
	y = origin.y + (radius * Math.sin(rotatedAngle));
	points.push(new SuperMap.Geometry.Point(x, y));
	var ring = new SuperMap.Geometry.LinearRing(points);
	ring.rotate(parseFloat(angel), origin);
	var geo = new SuperMap.Geometry.Collection([ ring ]);
	geo.origin = origin;
	geo.radius = radius;
	geo.r = r;
	geo.angel = angel;
	geo.sides = sides;
	geo.polygonType = "Curve";
	return geo;
};

function showFaultReasonInMap(lineObj) {
	closeInfoWin();
	var lineId = lineObj.lineId;
	$.getJSON("/rest/fault/getLineFaultCountById/" + lineId, function(result) {
		var lineFaultData = result;
		showFaultIocn(lineFaultData, lineObj);
		searchSelectObj(lineObj.lineName);
	});
}
function showFaultIocn(ld, lineObj) {
	var fts = [];
	var lfs = [];
	for ( var i in ld) {
		/*
		 * var remaker = ld[i].remark; var tapos = remaker.indexOf("塔"); // var
		 * tnum = remaker.replace(/[^0-9]/ig,""); var tnum =
		 * parseInt(remaker.substring(0,tapos).replace(/#/,'')); var towerno =
		 * tnum+""; if(towerno.substr(0,1) == "0"){ towerno = towerno.substr(1); }
		 */
		fts.push(ld[i].startPole);
		lfs.push(ld[i]);
	}
	var towers = [];
	for ( var i in lines500) {
		var ln = lines500[i];
		if (ln.lineId == lineObj.lineId) {
			towers = ln.towers;
			break;
		}
		;
	}
	var showTowers = [];
	for ( var j in towers) {
		var t = towers[j];
		for ( var f in fts) {
			if (fts[f] == t.towerno) {
				var obj = {
					t : towers[j],
					f : lfs[f]
				};
				showTowers.push(obj);
			}
			;
		}
	}
	drawFaultIcon(showTowers);
}
function drawFaultIcon(towers) {
	var heatPoints = [];
	for ( var i in towers) {
		var points = new SuperMap.Geometry.Point(towers[i].t.longitude,
				towers[i].t.latitude);
		heatPoints[i] = new SuperMap.Feature.Vector(points, null, {
			externalGraphic : towers[i].f.gif,
			graphicWidth : 50,
			graphicHeight : 50,
			graphicOpacity : 1,
		});
		heatPoints[i].data.type = "faultResaon";
		heatPoints[i].data.value = towers[i].f;
		showMulitFramedCloud(new SuperMap.LonLat(towers[i].t.longitude,
				towers[i].t.latitude), towers[i].t.towerno);
		showMulitFramedCloud(new SuperMap.LonLat(towers[i].t.longitude,
				towers[i].t.latitude), towers[i].t.towerno);
	}
	weatherLayer.addFeatures(heatPoints);
	weatherLayer.setVisibility(true);
	selectFeature.activate();
}
function showMulitFramedCloud(lonlat, content) {
	// var offset = new SuperMap.Pixel(-(size.w/2), -size.h);
	// var icon = new SuperMap.Icon(null, size, offset);
	var contentHTML = "<div style='width:80px;font-size:24px;text-align:center; opacity: 0.8'>";
	contentHTML += "#" + content;
	contentHTML += "</div>";
	var popup = new SuperMap.Popup.FramedCloud(null, lonlat, new SuperMap.Size(
			80, 20), contentHTML, null, false, null, true);
	multiInfoWins.push(popup);
	map.addPopup(popup);
}
function clearAll(showBottomMarquee, current) {
	$("#input_search").val('');
	map.removeAllPopup();
	clearQueryStatus();
	clearWeatherLayer();
	closeInfoWin();
	selectedLayer.removeAllFeatures();
	selectFeature.deactivate();
	searchObjLayer.removeAllFeatures();
	bar3DLayer.removeAllFeatures();
	pieLayer.removeAllFeatures();
	pieLayer.setVisibility(false);
	mapClusterLayer.removeAllFeatures();
	heatGridLayer.removeAllFeatures();
	heatMapLayer.removeAllFeatures();
	if (faultDiscMan) {
		faultDiscMan.hide();
	}
	if (dailyFaultMan) {
		dailyFaultMan.clear();
	}
	if (protectionStatusMan) {
		protectionStatusMan.hide();
	}
	if (typhoonDiscMan) {
		typhoonDiscMan.hide();
		typhoonDiscMan.hideChart();
	}
	if (typhoonForecastMan) {
		typhoonForecastMan.hide();
	}
	if (riskAlarmMan) {
		riskAlarmMan.hide();
	}
	if (weatherDiscMan) {
		weatherDiscMan.hide();
	}
	if (document.getElementById("statistics")) {
		$("#statistics").remove();
	}
	if (document.getElementById("bottom_title")) {
		$("#bottom_title").css('display', 'none');
	}
	if (showBottomMarquee) {
		// 重新获取故障数据
		faultAlarmMan.show();
	} else {
		faultAlarmMan.hide();
	}
	hoverDiv.hide();
}
function clearQueryStatus() {
	queryRectangleLayer.removeAllFeatures();
	queryRectangle.deactivate();
}
function clearWeatherLayer() {
	weatherLayer.removeAllFeatures();
	selectFeature.deactivate();
	affectSizeLayer.removeAllFeatures();// 清除气象信息
	closeInfoWin();
	weatherLayer.setVisibility(false);
	$("#affectObjDiv").css("display", "none");
}

function addDailyFault(item) {
	backToDefaultZoom();
	if (!dailyFaultMan) {
		dailyFaultMan = new DailyFaultMan();
	}
	dailyFaultMan.show(item);
}
function iceWarning() {
	backToDefaultZoom();
	// TODO 如果地图服务不可用，弹出alart，提示“当前功能不可用”
	if (!iceWarningMan) {
		iceWarningMan = new IceWarningManager();
	}
	iceWarningMan.show();
};
function thunderWarning() {
	backToDefaultZoom();
	// TODO 如果地图服务不可用，弹出alart，提示“当前功能不可用”
	if (!thunderWarningMan) {
		thunderWarningMan = new ThunderWarningManager();
	}
	thunderWarningMan.show();
};
function typhoonForecast() {
	backToDefaultZoom();
	// TODO 如果地图服务不可用，弹出alart，提示“当前功能不可用”
	if (!typhoonForecastMan) {
		typhoonForecastMan = new TyphoonForecastMan();
	}
	typhoonForecastMan.show();
}
function weatherWarning() {
	backToDefaultZoom();
	// TODO 如果地图服务不可用，弹出alart，提示“当前功能不可用”
	if (!weatherMan) {
		weatherMan = new weatherManager();
	}
	weatherMan.show();
};
function addFaultDistLayer(reason) {
	clearAll();
	backToDefaultZoom();
	if (!faultDiscMan) {
		faultDiscMan = new FaultDiscMan();
	}
	faultDiscMan.setReason(reason).show();
}
function weatherHistory() {
	// TODO 如果地图服务不可用，弹出alart，提示“当前功能不可用”
	if (!weatherHistoryMan) {
		weatherHistoryMan = new WeatherHistoryMan();
	}
	weatherHistoryMan.show();
}
function addWeatherDiscLayer(weather) {
	clearAll();
	backToDefaultZoom();
	// TODO 如果superMap不可用，需要另作处理
	if ('typhoon' == weather) {
		showTyphoonDiscLayer();
	} else {
		showWeatherDiscLayer(weather);
	}
}
function showTyphoonDiscLayer() {
	if (!typhoonDiscMan) {
		typhoonDiscMan = new TyphoonDiscMan();
	} else {
		typhoonDiscMan.show();
	}
}

function showWeatherDiscLayer(weather) {
	if (!weatherDiscMan) {
		weatherDiscMan = new WeatherDiscMan();
	}
	weatherDiscMan.setWeather(weather).show();
}
function getProtectionStatus() {
	backToDefaultZoom();
	if (!protectionStatusMan) {
		protectionStatusMan = new ProtectionStatusMan();
	}
	protectionStatusMan.show();
}

/**
 * map--风险告警--一次设备/二次设备
 * @param type 1：一次设备；2：二次设备
 * @returns
 */
function getRiskStations(type) {
	clearAll();
	backToDefaultZoom();
	if (!riskAlarmMan) {
		riskAlarmMan = new RiskAlarmMan();
	}
	riskAlarmMan.setDeviceType(type).show();
}
/**
 * map--风险评估--一次设备
 * @returns
 */
function getPrimaryRiskStations() {
	if (!riskEvaluateMan) {
		//   nwld-web/src/main/webapp/ui/map/riskEvaluate.js
		riskEvaluateMan = new RiskEvaluateManager();
	}
	riskEvaluateMan.getPrimaryRiskStations();
}
/**
 * map--风险评估--二次设备
 * @returns
 */
function getSecondaryRiskStations() {
	if (!riskEvaluateMan) {
		riskEvaluateMan = new RiskEvaluateManager();
	}
	riskEvaluateMan.getSecondaryRiskStations();
}
/**
 * map--风险评估--特维分析
 * @returns
 */
function getSpecialMaintanceStations() {
	if (!riskEvaluateMan) {
		riskEvaluateMan = new RiskEvaluateManager();
	}
	riskEvaluateMan.getSpecialMaintanceStations();
}
document.oncontextmenu = function(evt) {
	return false;
};
// 按钮的二级菜单
$("#btnBoxLeft li").mouseover(function() {
	if ($.contains(this, this.getElementsByTagName("ul")[0])) {
		$("#btnBoxRight").css("display", "none");
	}
});
$("#btnBoxLeft li").mouseout(function() {
	if ($.contains(this, this.getElementsByTagName("ul")[0])) {
		$("#btnBoxRight").css("display", "block");
	}
});

/**
 * 行波故障分布
 * @param reason 故障类型：行波故障分布
 * @returns
 */
function addTravelingFaultDistLayer(reason) {
	clearAll();
	backToDefaultZoom();
	if (!travelingFaultDiscMain) {
		travelingFaultDiscMain = new TravelingFaultDiscMain();
	}
	travelingFaultDiscMain.setReason(reason).show();
}
/**
 * 废弃代码
 */
/*
 * function getStations(){ var queryParam, queryBySQLParams, queryBySQLService;
 * queryParam = new SuperMap.REST.FilterParameter({ name : station500LayerName,
 * }); queryBySQLParams = new SuperMap.REST.QueryBySQLParameters({ queryParams : [
 * queryParam ] }); queryBySQLService = new
 * SuperMap.REST.QueryBySQLService(mapurl, { eventListeners : {
 * "processCompleted" : pqstation, "processFailed" : processFailed } });
 * queryBySQLService.processAsync(queryBySQLParams); }
 */
/*
 * function getLines(){ var queryParam, queryBySQLParams, queryBySQLService;
 * queryParam = new SuperMap.REST.FilterParameter({ name : line500LoopLayerName,
 * }); var queryParam2 = new SuperMap.REST.FilterParameter({ name :
 * line500LayerName, }); queryBySQLParams = new
 * SuperMap.REST.QueryBySQLParameters({ queryParams : [queryParam2,queryParam ]
 * }); queryBySQLService = new SuperMap.REST.QueryBySQLService(mapurl, {
 * eventListeners : { "processCompleted" : pqline, "processFailed" :
 * processFailed } }); queryBySQLService.processAsync(queryBySQLParams); }
 */

/*
 * function getTowers(){ var queryParam, queryBySQLParams, queryBySQLService;
 * queryParam = new SuperMap.REST.FilterParameter({ name :
 * "tower500_all@China4326", }); queryBySQLParams = new
 * SuperMap.REST.QueryBySQLParameters({ queryParams : [ queryParam ] });
 * queryBySQLService = new SuperMap.REST.QueryBySQLService(mapurl, {
 * eventListeners : { "processCompleted" : pqtower, "processFailed" :
 * processFailed } }); queryBySQLService.processAsync(queryBySQLParams); }
 */
/*
 * function pqstation(queryEventArgs) { var i, j, feature, result =
 * queryEventArgs.result; if (result && result.recordsets) { for (i = 0; i <
 * result.recordsets.length; i++) { if (result.recordsets[i].features) { for (j =
 * 0; j < result.recordsets[i].features.length; j++) { feature =
 * result.recordsets[i].features[j]; stations500.push(feature);
 * addToSearchs(feature.data.name,feature.data.name,true); } } } } } function
 * pqline(queryEventArgs) { var i, j, feature, result = queryEventArgs.result;
 * if (result && result.recordsets) { for (i = 0; i < result.recordsets.length;
 * i++) { if (result.recordsets[i].features) { for (j = 0; j <
 * result.recordsets[i].features.length; j++) { feature =
 * result.recordsets[i].features[j]; lines500.push(feature);
 * addToSearchs(feature.data.lineName,feature.data.lineName,true); } } } } }
 * function pqtower(queryEventArgs) { var i, j, feature, result =
 * queryEventArgs.result; if (result && result.recordsets) { for (i = 0; i <
 * result.recordsets.length; i++) { if (result.recordsets[i].features) { for (j =
 * 0; j < result.recordsets[i].features.length; j++) { feature =
 * result.recordsets[i].features[j]; towerpoints500.push(feature); } } } } }
 * function processFailed(e) { console.log(e.error.errorMsg); }
 */
/*
 * //异步调用时的方法，暂时废弃 function onMapClickQueryCompleted(queryEventArgs){ var
 * linefeatures = []; var lines = []; var station = null ; var i, j,result =
 * queryEventArgs.result; if (result && result.recordsets) { for (i = 0; i <
 * result.recordsets.length; i++) { if (result.recordsets[i].features) { for (j =
 * 0; j < result.recordsets[i].features.length; j++) { var feature =
 * result.recordsets[i].features[j]; if(feature.data.name){ station =
 * feature.data; break; } else { linefeatures.push(feature); } } } } }
 * if(station){ openStationMenuWin(station); } else if(linefeatures.length > 0){
 * for(var i in linefeatures){ var points = linefeatures[i].geometry.components;
 * if(points.length > 2){ for(var j =1; j < points.length;j++){ var p1 =
 * points[j-1]; var p2 = points[j]; var bounds = new SuperMap.Bounds();
 * bounds.extend(new SuperMap.Geometry.Point(p1.x,p1.y)); bounds.extend(new
 * SuperMap.Geometry.Point(p2.x,p2.y));
 * 
 * var isIntersects = bounds.intersectsBounds( currentQueryBounds );
 * if(isIntersects){ lines.push(linefeatures[i].data); break; } } } }
 * if(lines.length > 0){ openSelectLineWin(lines); } } currentQueryBounds =
 * null; }
 */
/*
 * //服务器端查询，暂时弃用 function findObjByBounds(queryBounds){ var queryParam1 = new
 * SuperMap.REST.FilterParameter({ name : line500LoopLayerName }); var
 * queryParam2 = new SuperMap.REST.FilterParameter({ name : line500LayerName });
 * var queryParam = new SuperMap.REST.FilterParameter({ name :
 * station500LayerName }); var queryByBoundsParams = new
 * SuperMap.REST.QueryByBoundsParameters({ queryParams : [
 * queryParam,queryParam1,queryParam2 ], bounds : queryBounds, });//
 * queryParams查询过滤条件参数数组。bounds查询范围 var queryService = new
 * SuperMap.REST.QueryByBoundsService(mapurl, { eventListeners : {
 * "processCompleted" : onMapClickQueryCompleted, "processFailed" :
 * processFailed } });
 * queryService.processAsync(queryByBoundsParams);//向服务端传递参数，然后服务端返回对象 }
 * function findObjByByGeometry(geoobj){ // var obj = findStation(bounds); //
 * if(obj){ // return obj; // } else { // obj = findLineByBounds(bounds); // } //
 * FilterParameter设置查询条件，name是必设的参数，（图层名称格式：数据集名称@数据源别名） var queryParam1 = new
 * SuperMap.REST.FilterParameter({ name : line500LoopLayerName }); var
 * queryParam2 = new SuperMap.REST.FilterParameter({ name : line500LayerName });
 * var queryParam = new SuperMap.REST.FilterParameter({ name :
 * station500LayerName }); var queryByGeometryParameters = new
 * SuperMap.REST.QueryByGeometryParameters( { queryParams : [
 * queryParam,queryParam1,queryParam2 ], geometry : geoobj.geometry,
 * spatialQueryMode : SuperMap.REST.SpatialQueryMode.INTERSECT }); var
 * queryService = new SuperMap.REST.QueryByGeometryService(mapurl, {
 * eventListeners : { "processCompleted" : onMapClickQueryCompleted,
 * "processFailed" : processFailed } });
 * queryService.processAsync(queryByGeometryParameters); }
 */
/*
 * function getPrimaryFaultsHis(){ clearAll(); //var bounds = new
 * SuperMap.Bounds(91.087439375,14.177615099145,127.73783,32.634646349145);
 * //map.zoomToExtent(bounds);
 * 
 * map.setCenter(new SuperMap.LonLat(107.09076285156, 23.808358533712), 7);
 * if(faultChartMan == null){ faultChartMan = new FaultChartMan();
 * faultChartMan.show(); }else{ faultChartMan.show(); } }
 */